<?php
/* ************************************************** *\
 * @company		: NovaITech							  *	
 * @author		: van.vo@novaitech.com				  * 
 * @copyright	: 2012								  * 
 * ================================================== *
 * @date		: 2/27/2012
 * @project		: CodeGenerater
 * @description	:
 *		- Generate code from fields.
 *
\* ************************************************** */
class generator extends MY_Controller
{
    function __construct( ){
		parent::__construct( );
	}
	
	function index(  ){
	   //$this->form_validation->set_rules( 'custom_action', 'custom_action', 'trim|required|xss_clean' );

        if($this->form_validation->run() == FALSE){    
            if( $this->input->post( 'generator' ) ){
                
                $table_current = $this->input->post('table'); // Curren table
                $layout_name = $this->input->post('layout_name');
                // -------------------------------------------
                // BEGIN: Get data from XML
                $actions = $this->xml_model->get_actions( $layout_name, 'actions' );
                $custom_actions = $this->xml_model->get_customactions( $layout_name, 'customactions' );
                $master_view = $this->xml_model->get_masterview( $layout_name, 'masterview');
                $detail_view = $this->xml_model->get_detailview( $layout_name, 'detailview');
                $fields = $this->xml_model->get_fields( $layout_name, 'fields');
                // END: Get data from XML
                // -------------------------------------------
                
                // -------------------------------------------
                // BEGIN: Get header data from XML
                $name_controller =   $this->xml_model->get_header_infor( $layout_name, 'name_controller');
                $name_view       =   $this->xml_model->get_header_infor( $layout_name, 'name_view');
                $validation      =   $this->xml_model->get_header_infor( $layout_name, 'name_validation_rule'); 
                $primarykey      =   $this->xml_model->get_header_infor( $layout_name, 'primarykey');
                // END  : Get header data from XML
                // -------------------------------------------  
               
                    
                // List file after generator 
                // -------------------------------------------  
                $all_files = array(
                               'validation'  =>  'application/config/form_validation.php',
                               'controller' =>  'application/controllers/'. $name_controller .'.php',
                               'model'      =>  'application/models/codegenerator_model.php',
                               'add'        =>  'application/views/'.$name_view.'_add.php',
                               'edit'       =>  'application/views/'.$name_view.'_edit.php',
                               'list'       =>  'application/views/'.$name_view.'_list.php');
         
                // -------------------------------------------
                // BEGIN: Templates
                // -------- 
                // Note:
                $template_files = array(
                    'basic'     =>  array(  
                        'controller'    =>  'templates/controller.php',
                        'list'          =>  'templates/list.php',
                        'edit'          =>  'templates/edit.php',
                        'add'           =>  'templates/add.php',
                        'validation'    =>  'templates/validation.php'),
                                                        
                    'standard'  =>  array(  
                        'controller'    =>  'templates/controller.php',
                        'list'          =>  'templates/list_standard.php',
                        'edit'          =>  'templates/edit.php',
                        'add'           =>  'templates/add.php',
                        'validation'    =>  'templates/validation.php'),                            
                );
                    
                $current_template = 'standard';
                // END: Templates
                // ---------------------------------------------
    
                    $err = 0;
                    
                    // Create form ADD
                    // -------------------------------------------    
                    $form_add = array();                 
                    foreach($fields as $field_id => $data){
                        if($primarykey !== $field_id){  // exclude primary key
                            $required = false;
                            if(strpos($data['rules'], 'required') !== FALSE){
                                $required = true;
                            }
                            if( array_key_exists( $field_id, $detail_view ) && !empty($detail_view[$field_id]['control'])){ //  find control in detail
                                
                                $field = $detail_view[$field_id];
                                
                                $form_add[] = create_form_add($field, $required, $data['label'] ); 
                            }else{
                                // create entry field (defaut)
                                $form_add[] = create_form_add(array(), $field_id, $data['label'], $required, 'add');
                            }
                        }
                    }

                    // Create form EDIT
                    // -------------------------------------------  
                    $form_edit = array();

                    foreach($detail_view as $field_id => $data){
                        if($primarykey !== $field_id){ // exclude primary key
                            $required = false;
                            if( strpos($fields[$field_id]['rules'], 'required') !== FALSE){
                                $required = true;
                            }

                            if(!empty($data['control'])){
                                $form_edit[] = create_form_add($data, $required, $fields[$field_id]['label'] );
                            }else{
                                $form_edit[] = create_form_add(array(), $field_id, $fields[$field_id]['label'], $required, 'edit');
                            }
                        }
                    }
                    
                    $fields_list[] = $primarykey;

                    // Create rules
                    // -------------------------------------------  
                    foreach($fields as $field_id => $data){
                        if($primarykey !== $field_id){
                            $form_val_add_data[] = "array(
                                'field' => '" . $field_id ."',
                                'label' => '" . $data['label'] . "',
                                'rules' => '" . $data['rules'] . "')";
                            $controller_form_data[] =  "'" . $field_id . "' => set_value('" . $field_id . "')";
                            if( array_key_exists($field_id, $detail_view) ){
                                $controller_form_editdata[] = "'" . $field_id . "' => \$this->input->post('" . $field_id ."')";
                                $form_val_edit_data[] = "array(
                                'field' => '" . $field_id ."',
                                'label' => '" . $data['label'] . "',
                                'rules' => '" . $data['rules'] . "')";
                            }
                            //$fields_list[ ] = $field_id;                        
                        }
                    }

                    


                    
                    // -------------------------------------------
                    // BEGIN: Create content validation
                    $fields_combine     = implode( ',', array_keys($master_view) );
                    $file_validation    = 'application/config/form_validation.php';
                    $option = array(
                                'form_val_add_data'     => $form_val_add_data,
                                'tablename'         => $table_current,
                                'file_validation'   => $file_validation);
                    if(isset($form_val_edit_data)){
                        $option['form_val_edit_data'] = $form_val_edit_data;
                    }
                    $form_content = generate_content_validation_file( $option, $file_validation );
                    // END: Create form validation
                    // -------------------------------------------
                    
                    $controller_path    = 'application/controllers/';
                    $model_path         = 'application/models/'; 
                    $view_path          = 'application/views/';                              


                    // -------------------------------------------
                    // BEGIN: Create Controller from template
                    $option = array(
                            'file_temp_controller'  =>  $template_files[ $current_template ][ 'controller' ],
                            'controller'            =>  $name_controller,
                            'view'                  =>  $name_view,
                            'table'                 =>  $table_current ,
                            'validation_add'            =>  $validation . "_add",
                            'validation_edit'            =>  $validation . "_edit",
                            'controller_form_data'  =>  $controller_form_data,
                            'controller_form_editdata'  => isset( $controller_form_editdata ) ? $controller_form_editdata : Null ,
                            'primaryKey'            =>  $primarykey,
                            //'fields_combine'        =>  $fields_combine,
                            'master_view'         => build_actions_to_string($master_view),
                            'fields_combine'        =>  implode(',', array_keys($fields)),
                            'master_limited'        =>  array_keys($master_view),
                            'action'                =>  build_actions_to_string($actions) ,
                            'custom_action'         =>  build_actions_to_string($custom_actions),
                           );   
                    $controller_content = generate_content_controller_file( $option );
                    $file_controller    = $controller_path . $name_controller . '.php';

                    // END: Create controller success
                    // -------------------------------------------
    
    
    // Create view/form, TODO, make this a function! and make a stop overwriting files
    // -------------------------------------------
                    
                    // -------------------------------------------
                    // BEGIN: View/List Form
                    $option = array(
                                'file_temp_list'    => $template_files[ $current_template ][ 'list' ],
                                'controller_name_l' => '{controller_name_l}',
                                'controller'        => $name_controller);   
                    $list_content = generate_content_list_form( $option );

                    // END: View/List Form
                    // -------------------------------------------
     
                   
                    // -------------------------------------------
                    // BEGIN: Add Form
                    $option = array(
                                'file_temp_add'     =>  $template_files[ $current_template ][ 'add' ],
                                'forms_inputs'      =>  '{forms_inputs}',
                                'add_form'          =>  $form_add);
                    $add_content = generate_content_add_form( $option );
                    // END: Add Form
                    // -------------------------------------------
                    
                    // -------------------------------------------
                    // BEGIN: Edit Form
                    $option = array(
                                'file_temp_edit'    =>  $template_files[ $current_template ][ 'edit' ],
                                'forms_inputs'      =>  '{forms_inputs}',
                                'primary'           =>  '{primary}',
                                'edit_form'         =>  $form_edit,
                                'primaryKey'        =>  $primarykey);
                    $edit_content = generate_content_edit_form( $option );
                    
                    // END: Edit Form
                    // -------------------------------------------
                    $write_files = array(
                                    'controller'    => array( $all_files['controller'], $controller_content),
                                    'view_edit'     => array( $all_files['edit'], $edit_content ),
                                    'view_list'     => array( $all_files['list'], $list_content ),
                                    'view_add'      => array( $all_files['add'], $add_content ),
                                    'form_validation'  => array( $all_files['validation'], $form_content ) 
                                    );
                                 
                    // Write files 
                    // -------------------------------------------
                    foreach( $write_files as $wf ){
                        if( writefile( $wf[ 0 ], $wf[ 1 ] ) ){
                            $err++;
                            echo writefile( $wf[ 0 ], $wf[ 1 ] );
     
                        }
                    }        
                                                       
                    if( $err > 0 ){
                        exit;
                    }else{
                        $data[ 'list_content' ] = $list_content;
                        $data[ 'add_content'  ] = $add_content;                                        
                        $data[ 'edit_content' ] = $edit_content;
                        $data[ 'controller'   ] = $controller_content;
                        $data[ 'table' ]        = $table_current;
                        $this->load->view( 'done', $data );
                    }   
                } // END if($this->input->post( 'generate' ))
        }			
	} // END Function
}
?>